<template>
	<view class="project-comment">
		<!-- 导航栏 -->
		<nav-bar></nav-bar>
		<!-- 服务信息区域 -->
		<view class="service-info">
			<image class="service-image" :src="serviceInfo.image || ''" mode="aspectFill"></image>
			<view class="service-detail">
				<view class="service-title">{{ serviceInfo.title || '筋骨同调推拿按摩体态矫正' }}</view>
				<view class="service-meta">
					<text class="store">{{ serviceInfo.store }}</text>
					<text class="technician">{{ serviceInfo.technician || '大刘老师' }}</text>
				</view>
				<view class="service-time">{{ serviceInfo.time || '2025年2月22日15:13' }}</view>
				<view class="service-price">
					<text class="original-price">¥{{ serviceInfo.originalPrice || '398' }}</text>
					<text class="member-price">会员价{{ serviceInfo.memberPrice || '298' }}</text>
				</view>
			</view>
		</view>

		<!-- 评分区域 -->
		<view class="rating-section">
			<view class="rating-row" v-for="(item, index) in ratingItems" :key="index">
				<image class="rating-image" :src="item.image" mode="aspectFill"></image>
				<view class="rating-content">
					<text class="rating-name">{{ item.name }}</text>
					<view class="rating-stars">
						<view class="star" v-for="starIndex in 5" :key="starIndex"
							:class="{ active: starIndex <= item.rating }" @tap="setRating(index, starIndex)">
							★
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 评价内容 -->
		<view class="comment-section">
			<view class="comment-title">亲，您满意的评价专业吗？环境怎么样，服务满意吗？</view>
			<textarea class="comment-input" v-model="commentContent" placeholder="请输入您的评价内容" maxlength="500"></textarea>
			<view class="word-count">{{ commentContent.length }}/500</view>
		</view>

		<!-- 图片/视频上传 -->
		<view class="upload-section">
			<view class="upload-title">上传图片/视频</view>
			<view class="upload-content">
				<view class="upload-list">
					<view class="upload-item" v-for="(item, index) in uploadedFiles" :key="index">
						<!-- 根据文件类型显示不同组件 -->
						<image v-if="item.type === 'image'" class="uploaded-image" :src="item.url" mode="aspectFill">
						</image>
						<video v-else-if="item.type === 'video'" class="uploaded-video" :src="item.url"
							:controls="false" :show-play-btn="true" :enable-progress-gesture="false" object-fit="cover">
						</video>
						<view class="delete-btn" @tap="deleteFile(index)">×</view>
					</view>
					<view class="upload-btn" @tap="chooseImage" v-if="uploadedFiles.length < 9">
						<image src="/static/icons/upload.png" mode="aspectFit"></image>
						<text>上传照片</text>
					</view>
					<view class="upload-btn" @tap="chooseVideo" v-if="!hasVideo">
						<image src="/static/icons/video.png" mode="aspectFit"></image>
						<text>上传视频</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 匿名评价 -->
		<view class="anonymous-section">
			<text>匿名评价</text>
			<switch @change="toggleAnonymous" :checked="isAnonymous" color="#C8022C" />
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn" @tap="submitComment">提交评价</view>
	</view>
</template>

<script>
	import NavBar from '@/components/nav-bar/nav-bar.vue'
	export default {
		components: {
			NavBar
		},
		data() {
			return {
				serviceInfo: {
					image: '',
					title: '',
					store: '',
					technician: '',
					time: '',
					originalPrice: '',
					memberPrice: ''
				},
				ratingItems: [{
						name: '服务评分',
						rating: 0,
						image: '/static/rating/1.png'
					},
					{
						name: '环境评分',
						rating: 0,
						image: '/static/rating/2.png'
					},
					{
						name: '专业评分',
						rating: 0,
						image: '/static/rating/3.png'
					},
					{
						name: '态度评分',
						rating: 0,
						image: '/static/rating/4.png'
					},
					{
						name: '综合评分',
						rating: 0,
						image: '/static/rating/5.png'
					}
				],
				commentContent: '',
				uploadedFiles: [],
				hasVideo: false,
				isAnonymous: false
			}
		},

		onLoad(options) {
			// 获取服务信息
			if (options.id) {
				this.loadServiceInfo(options.id)
				console.log(options.id)
			}
		},

		methods: {
			loadServiceInfo(id) {
				// 调用预约订单详情接口
				uni.request({
					url: `${uni.$config.baseUrl}/orders/orders/${id}`,
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							const orderData = res.data.data
							// 转换数据格式
							this.serviceInfo = {
								id: orderData.id,
								image: orderData.img || '',
								title: orderData.serviceName,
								projectId: orderData.serviceId,
								userId: orderData.userId,
								store: orderData.storeName,
								storeId: orderData.storeId,
								technician: orderData.technicianName,
								technicianId: orderData.technicianId,
								time: orderData.appointmentDate + "  " + orderData.appointmentTime,
								originalPrice: orderData.servicePrice,
								memberPrice: orderData.servicePrice
							}
						} else {
							uni.showToast({
								title: res.data.msg || '获取预约信息失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('获取预约信息失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					}
				})
			},

			setRating(itemIndex, rating) {
				this.ratingItems[itemIndex].rating = rating
			},

			chooseImage() {
				uni.chooseImage({
					count: 9 - this.uploadedFiles.length,
					success: (res) => {
						const newFiles = res.tempFilePaths.map(path => ({
							type: 'image',
							url: path
						}))
						this.uploadedFiles.push(...newFiles)
					}
				})
			},

			async chooseVideo() {
				try {
					// 选择视频
					const res = await uni.chooseVideo({
						compressed: true,
						sourceType: ['camera', 'album']
					})

					// 显示上传中提示
					uni.showLoading({
						title: '上传中...',
						mask: true
					})

					// 上传视频文件
					const uploadRes = await uni.uploadFile({
						url: `${uni.$config.baseUrl}/minio/upload/video`,
						filePath: res.tempFilePath,
						name: 'file',
						formData: {}
					})

					const data = JSON.parse(uploadRes.data)
					if (data.code === 200) {
						// 上传成功，添加到文件列表
						this.uploadedFiles.push({
							type: 'video',
							url: data.url // 使用返回的视频URL
						})
						this.hasVideo = true

						uni.showToast({
							title: '上传成功',
							icon: 'success'
						})
					} else {
						throw new Error(data.msg || '上传失败')
					}
				} catch (err) {
					console.error('上传视频失败:', err)
					uni.showToast({
						title: err.message || '上传失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			deleteFile(index) {
				const file = this.uploadedFiles[index]
				if (file.type === 'video') {
					this.hasVideo = false
				}
				this.uploadedFiles.splice(index, 1)
			},

			toggleAnonymous(e) {
				this.isAnonymous = e.detail.value
			},

			async submitComment() {
				// 验证必填项
				if (!this.validateForm()) {
					return
				}

				// 显示加载中
				uni.showLoading({
					title: '提交中...'
				})

				try {
					// 提交评价
					const commentData = {
						orderId: this.serviceInfo.id,
						projectId: this.serviceInfo.projectId,
						userId: this.serviceInfo.userId,
						storeId: this.serviceInfo.storeId,
						technicianId: this.serviceInfo.technicianId,
						serviceRating: this.ratingItems[0].rating,
						environmentRating: this.ratingItems[1].rating,
						professionalRating: this.ratingItems[2].rating,
						attitudeRating: this.ratingItems[3].rating,
						overallRating: this.ratingItems[4].rating,
						commentContent: this.commentContent,
						mediaUrls: this.uploadedFiles.map(file => file.url).join(','),
						isAnonymous: this.isAnonymous ? 1 : 0,
						status: 1,
						createBy: uni.getStorageSync('userInfo').userName || ''
					}

					await this.submitCommentData(commentData)

					uni.showToast({
						title: '评价成功',
						icon: 'success'
					})

					// 返回上一页
					setTimeout(() => {
						uni.navigateTo({
							url: `/pages/my-comment/my-comment`
						})
					}, 1500)

				} catch (error) {
					uni.showToast({
						title: error.message || '评价失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			validateForm() {
				// 验证评分
				if (this.ratingItems.some(item => item.rating === 0)) {
					uni.showToast({
						title: '请完成所有评分项',
						icon: 'none'
					})
					return false
				}

				// 验证评价内容
				if (!this.commentContent.trim()) {
					uni.showToast({
						title: '请输入评价内容',
						icon: 'none'
					})
					return false
				}

				return true
			},

			async uploadFiles() {
				const uploadPromises = this.uploadedFiles.map(file => {
					return new Promise((resolve, reject) => {
						// 检查文件类型
						if (file.type === 'video') {
							reject(new Error('只能上传图片文件'))
							return
						}

						// 获取文件信息
						uni.getFileInfo({
							filePath: file.url,
							success: (fileInfo) => {
								// 检查文件大小（2MB = 2 * 1024 * 1024）
								if (fileInfo.size > 2 * 1024 * 1024) {
									reject(new Error('文件大小不能超过2MB'))
									return
								}

								// 上传文件
								uni.uploadFile({
									url: `${uni.$config.baseUrl}/minio/upload`,
									filePath: file.url,
									name: 'file',
									formData: {
										'Content-Type': 'image/jpeg' // 设置文件类型
									},
									success: (res) => {
										try {
											const data = JSON.parse(res.data)
											if (data.code === 200) {
												resolve(data.url)
											} else {
												reject(new Error(data.msg ||
													'文件上传失败'))
											}
										} catch (e) {
											reject(new Error('解析响应数据失败'))
										}
									},
									fail: () => {
										reject(new Error('文件上传失败'))
									}
								})
							},
							fail: () => {
								reject(new Error('获取文件信息失败'))
							}
						})
					})
				})

				try {
					const urls = await Promise.all(uploadPromises)
					return urls.filter(url => url) // 过滤掉可能的空值
				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					})
					throw error
				}
			},

			async submitCommentData(data) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: `${uni.$config.baseUrl}/comments/comments`,
						method: 'POST',
						data,
						success: (res) => {
							if (res.data.code === 200) {
								resolve(res.data)
							} else {
								reject(new Error(res.data.msg || '评价提交失败'))
							}
						},
						fail: () => {
							reject(new Error('网络请求失败'))
						}
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	.project-comment {
		min-height: 100vh;
		background: #F8F8F8;
		padding-bottom: 120rpx;

		.service-info {
			background: #FFFFFF;
			padding: 30rpx;
			display: flex;
			margin-bottom: 20rpx;

			.service-image {
				width: 200rpx;
				height: 200rpx;
				border-radius: 8rpx;
				margin-right: 20rpx;
			}

			.service-detail {
				flex: 1;

				.service-title {
					font-size: 32rpx;
					color: #333;
					font-weight: 500;
					margin-bottom: 10rpx;
				}

				.service-meta {
					font-size: 26rpx;
					color: #666;
					margin-bottom: 10rpx;

					.technician {
						margin-left: 20rpx;
					}
				}

				.service-time {
					font-size: 26rpx;
					color: #999;
					margin-bottom: 10rpx;
				}

				.service-price {
					.original-price {
						font-size: 32rpx;
						color: #C8022C;
						font-weight: bold;
						margin-right: 20rpx;
					}

					.member-price {
						font-size: 26rpx;
						color: #999;
					}
				}
			}
		}

		.rating-section {
			background: #FFFFFF;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.rating-row {
				display: flex;
				align-items: center;
				margin-bottom: 30rpx;

				&:last-child {
					margin-bottom: 0;
				}

				.rating-image {
					width: 80rpx;
					height: 80rpx;
					border-radius: 8rpx;
					margin-right: 20rpx;
				}

				.rating-content {
					flex: 1;
					display: flex;
					align-items: center;

					.rating-name {
						font-size: 28rpx;
						color: #333;
						margin-right: 20rpx;
					}

					.rating-stars {
						display: flex;
						align-items: center;

						.star {
							font-size: 40rpx;
							color: #ddd;
							margin-right: 10rpx;

							&.active {
								color: #FFD700;
							}
						}
					}
				}
			}
		}

		.comment-section {
			background: #FFFFFF;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.comment-title {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 20rpx;
			}

			.comment-input {
				width: 100%;
				height: 200rpx;
				background: #F8F8F8;
				border-radius: 8rpx;
				padding: 20rpx;
				font-size: 28rpx;
				color: #333;
			}

			.word-count {
				text-align: right;
				font-size: 24rpx;
				color: #999;
				margin-top: 10rpx;
			}
		}

		.upload-section {
			background: #FFFFFF;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.upload-title {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 20rpx;
			}

			.upload-content {
				.upload-list {
					display: flex;
					flex-wrap: wrap;

					.upload-item {
						width: 160rpx;
						height: 160rpx;
						margin-right: 20rpx;
						margin-bottom: 20rpx;
						position: relative;
						overflow: hidden; // 添加overflow防止视频超出容器

						.uploaded-image,
						.uploaded-video {
							width: 100%;
							height: 100%;
							border-radius: 8rpx;
						}

						.uploaded-video {
							object-fit: cover;
						}

						.delete-btn {
							position: absolute;
							top: -20rpx;
							right: -20rpx;
							width: 40rpx;
							height: 40rpx;
							background: rgba(0, 0, 0, 0.5);
							border-radius: 50%;
							color: #FFFFFF;
							display: flex;
							align-items: center;
							justify-content: center;
							font-size: 24rpx;
						}
					}

					.upload-btn {
						width: 160rpx;
						height: 160rpx;
						background: #F8F8F8;
						border-radius: 8rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						margin-right: 20rpx;
						margin-bottom: 20rpx;

						image {
							width: 60rpx;
							height: 60rpx;
							margin-bottom: 10rpx;
						}

						text {
							font-size: 24rpx;
							color: #999;
						}
					}
				}
			}
		}

		.anonymous-section {
			background: #FFFFFF;
			padding: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			text {
				font-size: 28rpx;
				color: #333;
			}
		}

		.submit-btn {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 100rpx;
			background: #C8022C;
			color: #FFFFFF;
			font-size: 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			&:active {
				opacity: 0.9;
			}
		}
	}
</style>